from timeit import Timer
from Primes import Divisors

import sys
import math


def Problem():
    """
    Let d(n) be defined as the sum of proper divisors of n 
    (numbers less than n which divide evenly into n).
    If d(a) = b and d(b) = a, where a != b, then a and b are 
    an amicable pair and each of a and b are called amicable numbers.
    
    For example, the proper divisors of 220 are 
    1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. 
    The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
    
    Evaluate the sum of all the amicable numbers under 10000.
    """


        
    pairs = dict()
    amicablePairs = []
    for x in xrange(2,10000):
        #Get divisors
        div = Divisors(x)
        #print x, sum(div), div
        div = sum(div)

        #If the sum equals another number that same sum of divisors
        if div in pairs and pairs[div] == x:
            amicablePairs.append((x, div))  
        else:
            #Add to list otherwise
            pairs[x] =  div

    
    print amicablePairs
    ans = sum(map(lambda (x,y): x+y , amicablePairs)) 
    
    print "Answer for Problem 21 = %d" % (ans,)
    
    
if __name__ == "__main__":
    t = Timer(setup='from __main__ import Problem', stmt='Problem()').timeit(1)
    print "Execution time = %0.3f seconds" %(t,)